package com.example.service;

import com.example.entity.Product;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class ProductService {
    private final Map<Long, Product> productMap = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong();

    public Product create(Product product) {
        product.setId(idGenerator.incrementAndGet());
        productMap.put(product.getId(), product);
        return product;
    }

    public Product getProductById(Long id) {
        return productMap.get(id);
    }

    public List<Product> getAllProducts() {
        return new ArrayList<>(productMap.values());
    }

    public boolean updateStock(Long id, int quantity) {
        Product product = productMap.get(id);
        if (product != null && product.getStock() >= quantity) {
            product.setStock(product.getStock() - quantity);
            productMap.put(id, product);
            return true;
        }
        return false;
    }
} 